<script setup lang="ts">
import TargetCard from "@/components/TargetCard.vue";
import { setup } from "@/utils/setup.js";
import md5 from "crypto-js/md5";
import {
  NButton,
  NCard,
  NDivider,
  NDynamicInput,
  NForm,
  NFormItem,
  NInput,
  NInputGroup,
  NInputGroupLabel,
  NP,
  NSpace,
} from "naive-ui";
import { ref, watchEffect } from "vue";

const { masterStore, configStore, storageStore, router } = setup();

const token = ref("");

function updateToken(token: string) {
  if (configStore.config !== undefined) {
    configStore.config.token = token !== "" ? md5(token).toString() : "";
  }
}

function logout() {
  masterStore.token = "";
  masterStore.$reset();
  configStore.$reset();
  storageStore.$reset();
  router.push({ name: "login" });
}

watchEffect(() => {
  const local = configStore.config?.token;
  const cache = configStore.cache.config.value?.token;
  if (local === cache) {
    token.value = "";
  }
});
</script>

<template>
  <NSpace style="margin: 16px" size="large" vertical>
    <TargetCard id="password" size="small" title="密码">
      <NP>密码控制。</NP>
      <NInputGroup>
        <NInputGroupLabel>新密码</NInputGroupLabel>
        <NInput v-if="configStore.config === undefined" disabled />
        <NInput v-else v-model:value="token" @update-value="updateToken" />
      </NInputGroup>
    </TargetCard>
    <TargetCard id="cloudflareId" size="small" title="Cloudflare ID">
      <NP>
        Cloudflare 账号 ID，用于自动跳转
        <NButton
          size="small"
          tag="a"
          href="https://dash.cloudflare.com/"
          target="_blank"
        >
          Cloudflare 面板
        </NButton>
        。
      </NP>
      <NInputGroup>
        <NInputGroupLabel>ID</NInputGroupLabel>
        <NInput v-if="configStore.config === undefined" disabled />
        <NInput v-else v-model:value="configStore.config.cloudflareId" />
      </NInputGroup>
    </TargetCard>
    <TargetCard size="small" title="默认参数">
      <NP>默认参数控制。</NP>
      <NForm label-placement="left" label-width="auto">
        <NFormItem label="SSH 登录密钥">
          <NDynamicInput v-if="configStore.config === undefined" :max="0" />
          <NDynamicInput
            v-else
            v-model:value="
              configStore.config.default.host.ssh.server.allowedKeys
            "
            show-sort-button
          />
        </NFormItem>
        <NFormItem label="环境变量">
          <NDynamicInput v-if="configStore.config === undefined" :max="0" />
          <NDynamicInput
            v-else
            v-model:value="configStore.config.default.host.envs"
            preset="pair"
            key-placeholder="环境变量键"
            value-placeholder="环境变量值"
            show-sort-button
          />
        </NFormItem>
      </NForm>
    </TargetCard>
    <TargetCard size="small" title="账号">
      <NP>账号控制。</NP>
      <NButton @click="logout()">退出登录</NButton>
    </TargetCard>
  </NSpace>
</template>
